package com.yuntianshi.service.impl;

import com.yuntianshi.common.PageResult;
import com.yuntianshi.dao.MemberDao;
import com.yuntianshi.pojo.Member;
//import User;
import com.yuntianshi.service.MemberService;
import com.yuntianshi.utils.MD5Utils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;

    //根据手机号查询会员
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }
    //新增会员
    public void add(Member member) {
        if(member.getPassword() != null){
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }
        if (member.getFileNumber()==null){
            member.setFileNumber(member.getPhoneNumber());
        }
        memberDao.add(member);
    }
    //根据月份统计会员数量
    public List<Integer> findMemberCountByMonth(List<String> month) {
        List<Integer> list = new ArrayList<>();
        for (String m : month) {
            try {
                String date_str = m + "-10";
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                calendar.setTime(sdf.parse(date_str));
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 0);
                // 获取当月最后一天
                String lastDayOfMonth = sdf.format(calendar.getTime());
                Integer count = memberDao.findMemberCountBeforeDate(lastDayOfMonth);
                list.add(count);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        //        完成分页查询，基于MyBatis框架提供的分页助手插件完成
        if (queryString!=null&&queryString.length()>0){
            PageHelper.startPage(1,pageSize);
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<Member> page = memberDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(Integer id) {
        memberDao.deleteById(id);
    }

    @Override
    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }
}
